//
//  ZPMineInformationVC.m
//  ZPIOSEducation
//
//  Created by mini1 on 2017/1/4.
//  Copyright © 2017年 mini1. All rights reserved.
//

#import "ZPMineInformationVC.h"
#import "ZPMineEditIDViewController.h"
#import "ZPSelectCityVC.h"
#import "ZPSelectGradeVC.h"
#import "ZPChangePwdViewController.h"
#import "ZPUpdateSetPwdViewController.h"
#define zHeaderActionSheetTag    1000

@interface ZPMineInformationVC ()<UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
    NSString *_headerImagePath;
    NSMutableDictionary *_menberInfoDic;
    MBProgressHUD       *_HUD;
    NSString            *fullPath;      // 头像路径
}

@property (weak, nonatomic) IBOutlet UIImageView *Arrow1;
@property (weak, nonatomic) IBOutlet UIImageView *Arrow2;
@property (weak, nonatomic) IBOutlet UIButton *iconBtn;
@property (weak, nonatomic) IBOutlet UIImageView *userIcon;
@property (weak, nonatomic) IBOutlet UILabel *userName;
@property (weak, nonatomic) IBOutlet UILabel *userIdentity;
@property (weak, nonatomic) IBOutlet UILabel *seleceCity;
@property (weak, nonatomic) IBOutlet UILabel *selectGrade;
@property (weak, nonatomic) IBOutlet UILabel *updatePawd;

@end

@implementation ZPMineInformationVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    // 姓名不能二次编译
    _menberInfoDic = [[ZPAuthStore sharedZPAuthStore] userToDic];
    NSString *userName = _menberInfoDic[@"userName"];
    if (userName && ![userName isEqual:[NSNull null]] && ![userName isEqual:@"<null>"])
    {
        self.userName.userInteractionEnabled = NO;
        self.Arrow1.hidden = YES;
    }
    
    [self addGestureRecognizer];
    
    self.title = @"我的资料";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"zhenpin_back"] style:UIBarButtonItemStylePlain target:self action:@selector(clickBackButtonItem)];
    ViewRadius(self.userIcon, self.userIcon.xj_width / 2);
    
    [self getStudentById:[_menberInfoDic objectForKey:@"stuId"]];
}


#pragma mark - <viewWillAppear>
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    

}


-(void)getStudentById:(NSString *)sid{
    
     [self  showHudithString:@"加载中..."];
    [[ZPNetworking sharedZPNetworking] GET:APIUC@"user/getStudentById.json" parameters:@{@"id":sid} progress:nil success:^(id  _Nonnull responseObject) {
        if ([[responseObject  objectForKey:@"code"] integerValue] == 200) {
            NSLog(@"responseObject=responseObject=====%@",responseObject);
            NSDictionary  *resultDic = [NSMutableDictionary changeType:[responseObject  objectForKey:@"result"]];
            
            NSString *homePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/UserInfo.plist"];
            NSMutableDictionary *dataDic = [[NSDictionary dictionaryWithContentsOfFile:homePath] mutableCopy];
            [dataDic  setObject:[NSString  stringWithFormat:@"%@",[resultDic  objectForKey:@"grade"]] forKey:@"grade"];
            [dataDic  setObject:[NSString  stringWithFormat:@"%@",[resultDic  objectForKey:@"headUrl"]] forKey:@"headUrl"];
            [dataDic  setObject:[NSString  stringWithFormat:@"%@",[resultDic  objectForKey:@"name"]] forKey:@"stuName"];
            [dataDic  setObject:[NSString  stringWithFormat:@"%@",[resultDic  objectForKey:@"stuId"]] forKey:@"stuId"];
            [dataDic  setObject:[NSString  stringWithFormat:@"%@",[resultDic  objectForKey:@"stuNumber"]] forKey:@"stuNum"];
            [dataDic  writeToFile:homePath atomically:YES];
            
            [[ZPAuthStore sharedZPAuthStore] resetUserInfoDictionary];
            [[ZPAuthStore sharedZPAuthStore] setWebViewCookiesWithType:1];
            
            self.userName.text =[resultDic  objectForKey:@"name"];
            NSString *cityName = [resultDic  objectForKey:@"cityName"];
            self.seleceCity.text =[cityName isEqualToString:@""] ? @"请选择城市" : cityName;
            self.selectGrade.text =[resultDic  objectForKey:@"gradeName"];
            NSString *idCard = [NSMutableDictionary changeType:[resultDic objectForKey:@"idCard"]];
            if(![idCard isEqualToString:@""]){
                self.Arrow2.hidden = YES;
                if(idCard.length > 16){
                    NSString *cardNum = [idCard stringByReplacingCharactersInRange:NSMakeRange(6, 8) withString:@"****"];
                     self.userIdentity.text =cardNum;
                }else{
                    self.userIdentity.text =idCard;
                }
            }
            [self.userIcon sd_setImageWithURL:[NSURL URLWithString:[resultDic objectForKey:@"headUrl"]] placeholderImage:[UIImage imageNamed:@"headportrait"] options:SDWebImageRetryFailed];
            [self hiddenHud];
//            [[NSNotificationCenter defaultCenter] postNotificationName:@"logOnNotification" object:nil];
            
        }else{
            [self hiddenHud];
        }
    } failure:^(NSError * _Nonnull error) {
        [self hiddenHud];

    }];
}


-(void)saveStudentInfo:(NSString*) value forParam:(NSString *) param{
    
    if(![self isHudShow]){
        [self  showHudithString:@"提交修改..."];
    }
    NSDictionary *params = @{@"id":[[[ZPAuthStore sharedZPAuthStore] userToDic] objectForKey:@"stuId"],
                             @"value":value,
                             @"param":param};
    [[ZPNetworking sharedZPNetworking] POST:APIUC@"user/updateStudent.json" parameters:params progress:^(NSProgress * _Nullable progress) {
        
    } success:^(id  _Nonnull responseObject) {
        if ([[responseObject objectForKey:@"code"] integerValue]==200) {
           BOOL isOK =  [[[responseObject  objectForKey:@"result"]objectForKey:@"isOk"]boolValue];
            if(isOK){
                NSString *homePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/UserInfo.plist"];
                NSMutableDictionary *dataDic = [[NSDictionary dictionaryWithContentsOfFile:homePath] mutableCopy];
                if([@"city" isEqualToString:param]){
                    [dataDic  setObject:param forKey:@"city"];
                }else if([@"grade" isEqualToString:param]){
                  [dataDic  setObject:param forKey:@"grade"];
                }else if([@"id_card" isEqualToString:param]){
                    ZPMineEditIDViewController *editVc = [[ZPMineEditIDViewController alloc] init];
                    [editVc dismissViewControllerAnimated:YES completion:^{
                        
                    }];
                }else if([@"head_url" isEqualToString:param]){
                    [self getStudentById:[[[ZPAuthStore sharedZPAuthStore] userToDic] objectForKey:@"stuId"]];
                }
                [dataDic  writeToFile:homePath atomically:YES];
                
                [[ZPAuthStore sharedZPAuthStore] resetUserInfoDictionary];
                [[ZPAuthStore sharedZPAuthStore] setWebViewCookiesWithType:1];
                [self hiddenHud];
                
                [ZPPromptView showMessage:@"修改成功"];
            }else{
                [self hiddenHud];
                [ZPPromptView showMessage:@"修改失败"];
                
            }
        }else{
            [self hiddenHud];
            [ZPPromptView showMessage:@"修改失败"];
        }
    } failure:^(NSError * _Nonnull error) {
        [self hiddenHud];
        
    }];
}


- (void)addGestureRecognizer
{
    UITapGestureRecognizer *userIconTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(updateIcon:)];
    [self.iconBtn addGestureRecognizer:userIconTap];
    
    UITapGestureRecognizer *userNameTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(inputName:)];
    [self.userName addGestureRecognizer:userNameTap];
    
    UITapGestureRecognizer *userIdentityTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(inputIdentity:)];
    [self.userIdentity addGestureRecognizer:userIdentityTap];
    
    UITapGestureRecognizer *selectCityTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectCity:)];
    [self.seleceCity addGestureRecognizer:selectCityTap];
    
    UITapGestureRecognizer *selectGradeTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectGrade:)];
    [self.selectGrade addGestureRecognizer:selectGradeTap];
    
    UITapGestureRecognizer *updatePawdTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(updatePawd:)];
    [self.updatePawd addGestureRecognizer:updatePawdTap];
    
}

// 更改头像
- (void)updateIcon:(UIGestureRecognizer *)tap
{
    [self selectPhoto];
}

// 输入姓名
- (void)inputName:(UIGestureRecognizer *)tap
{
    ZPMineEditIDViewController *editVc = [[ZPMineEditIDViewController alloc] init];
    editVc.navString = @"姓名";
    editVc.flag = 100;
    editVc.passValue = ^(NSString *string)
    { // block 回调传值
        self.userName.text = string;
        
    };
    [self.navigationController pushViewController:editVc animated:YES];
}

// 输入身份证
- (void)inputIdentity:(UIGestureRecognizer *)tap
{
    if([self.userIdentity.text isEqualToString:@""] || [self.userIdentity.text isEqualToString:@"请输入学生身份证"]){
        ZPMineEditIDViewController *editVc = [[ZPMineEditIDViewController alloc] init];
        editVc.navString = @"身份证";
        editVc.flag = 200;
        editVc.passValue = ^(NSString *string)
        { // block 回调传值
            self.userIdentity.text = string;
            [self saveStudentInfo:string forParam:@"id_card"];
        };
        [self.navigationController pushViewController:editVc animated:YES];
    }else{
        return;
    }
}

// 选择城市
- (void)selectCity:(UIGestureRecognizer *)tap
{
    ZPSelectCityVC *selectVc = [[ZPSelectCityVC alloc] init];
    // block传值
    selectVc.valueBlock1 = ^(NSString *string,NSInteger ID){
        self.seleceCity.text = string;
        [self saveStudentInfo:[NSString stringWithFormat:@"%ld",ID] forParam:@"city"];

    };
    [self.navigationController pushViewController:selectVc animated:YES];
//    [self presentViewController:selectVc animated:YES completion:nil];
}

// 选择年级
- (void)selectGrade:(UIGestureRecognizer *)tap
{
    ZPSelectGradeVC *selectVc = [[ZPSelectGradeVC alloc] init];
    // block传值
    selectVc.valueBlock1 = ^(NSString *string,NSInteger ID)
    {
        self.selectGrade.text = string;
        [self saveStudentInfo:[NSString stringWithFormat:@"%ld",ID] forParam:@"grade"];
    };
    [self presentViewController:selectVc animated:YES completion:nil];
    
    
}

//修改密码
- (void)updatePawd:(UIGestureRecognizer *)tap
{
    ZPChangePwdViewController *changerPwdVc = [[ZPChangePwdViewController alloc] init];
    changerPwdVc.flag = 101;
    [self.navigationController pushViewController:changerPwdVc animated:YES];
    
//    ZPUpdateSetPwdViewController *vc = [[ZPUpdateSetPwdViewController alloc]init];
//    [self.navigationController pushViewController:vc animated:YES];
}


- (void)clickBackButtonItem {
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - <UIAlertActioncontroller>
- (void)selectPhoto {
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"编辑头像" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles: @"拍照",@"从手机相册选择",nil];
    actionSheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
    actionSheet.tag = zHeaderActionSheetTag;
    [actionSheet showInView:self.view];
    
}


- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (actionSheet.tag == zHeaderActionSheetTag)
    {
        if (buttonIndex == 0)
        {
            [self openCamera];
        }
        else if (buttonIndex == 1)
        {
            [self openpicLibrary];
        }
    }
}


// 访问相机
- (void)openCamera
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        UIImagePickerController * picker = [[UIImagePickerController alloc]init];
        picker.delegate = self;
        picker.allowsEditing = YES;
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:picker animated:YES completion:nil];
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"你没有摄像头" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    }
}


// 访问相册
- (void)openpicLibrary
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
    {
        UIImagePickerController * picker = [[UIImagePickerController alloc]init];
        picker.delegate = self;
        picker.allowsEditing = YES;
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:picker animated:YES completion:nil];
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"你没有摄像头" delegate:nil cancelButtonTitle:@"Drat!" otherButtonTitles:nil];
        [alert show];
    }
}


// 选择完图片或者拍照完成后按确定按钮回调方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary<NSString *,id> *)editingInfo
{
    [self dismissViewControllerAnimated:YES completion:nil];
}


// 选择完图片代理回调
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    NSString *tempName = [NSString stringWithFormat:@"%u_share.png",arc4random()];
    [self saveImage:image withName:tempName];
    [self dismissViewControllerAnimated:YES completion:nil];
}


// 取消选择调用方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark - <保存图片到沙盒>
- (void)saveImage:(UIImage *)currentImage withName:(NSString *)imageName
{
    //压缩图片然后再上传(1.0代表无损 0~~1.0区间)
    NSData *imageData = UIImageJPEGRepresentation(currentImage, 0.5);
    // 获取沙盒目录
    fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
    
    // 将图片写入文件
    [imageData writeToFile:fullPath atomically:NO];
    
    self.userIcon.image = [UIImage imageWithContentsOfFile:fullPath];
    
    // 上传头像
     [self uploadImage:fullPath];
}



// 上传用户头像
- (void)uploadImage:(NSString *)imagePath
{
    [self showHudithString:@"正在上传头像..."];
    
    AFHTTPSessionManager *manager=[AFHTTPSessionManager manager];
    [manager POST:APIUC@"image/addImage.json" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        [formData appendPartWithFileURL:[NSURL fileURLWithPath:imagePath] name:@"images" error:nil];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        self.userIcon.image=[UIImage imageWithContentsOfFile:imagePath];
        
        if ([[responseObject objectForKey:@"code"] integerValue] == 200)
        {
            NSString *picName = [[[[responseObject objectForKey:@"result"] objectForKey:@"result"]objectAtIndex:0]objectForKey:@"value"];
            [self saveStudentInfo:picName forParam:@"head_url"];
        }
        else
        {
            [ZPPromptView showMessage:[responseObject objectForKey:@"codeMsg"]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [ZPPromptView showMessage:@"上传失败，请检查您的网络设置"];
    }];
}


// 修改用户头像
-(void)changeUserHeadImageWithImageUrl:(NSString *)imageUrl
{
    NSDictionary *params=@{
                           @"memberid": [_menberInfoDic objectForKey:@"memberId"],
                           @"access_token": [[[ZPAuthStore sharedZPAuthStore] userToDic]valueForKey:@"token"],
                           @"url":imageUrl,
                           @"v":@"2.0"
                           };
    
    _HUD.hidden = NO;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager POST:APIUC@"user/updateStudent.json" parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
     {
         _HUD.hidden = YES;
         
         if ([[responseObject objectForKey:@"code"] integerValue] == 200)
         {
             if (responseObject[@"result"][@"pointOut"] && ![responseObject[@"result"][@"pointOut"] isEqual:[NSNull null]]) {
                 
                 [ZPPromptView showMessage:responseObject[@"result"][@"pointOut"]];
             } else {
                 
                 [ZPPromptView showMessage:@"修改头像成功"];
             }
         } else {
             [ZPPromptView showMessage:[responseObject objectForKey:@"codeMsg"]];
         }
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         
         _HUD.hidden = YES;
         [ZPPromptView showMessage:@"请检查您的网络设置"];
     }];
}



#pragma mark - <点击cell进去编辑身份证界面>
- (void)editID {
    ZPMineEditIDViewController *editidVc = [[ZPMineEditIDViewController alloc] init];
    [self.navigationController pushViewController:editidVc animated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
